package com.zhu.interceptor;

import com.zhu.config.GuavaCacheManager;
import com.zhu.exception.AppRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * zhuhuanle
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    GuavaCacheManager<String, String> cacheManager;


    @Override
    public boolean preHandle(
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse,
            Object object) { // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("xatoken");
        log.info("xatoken:{}", token);
        // 执行认证
        /*if (token == null) {
            throw new AppRuntimeException("401", "账号未登录");
        }*/
        try {
            // todo 校验token
            /*final String s = cacheManager.get(token);
            if (StringUtils.isEmpty(s)) {
                throw new AppRuntimeException("408", "登录已过期");
            }*/
            return true;
        } catch (AppRuntimeException e) {
            throw new AppRuntimeException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.info("解析token出错{}", e);
            throw new AppRuntimeException("401", "获取用户权限出错");
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }


}
